package com.tt5.services.starter

import io.vertx.config.ConfigRetriever
import io.vertx.core.impl.logging.Logger
import io.vertx.core.impl.logging.LoggerFactory
import io.vertx.kotlin.config.configRetrieverOptionsOf
import io.vertx.kotlin.config.configStoreOptionsOf
import io.vertx.kotlin.core.json.jsonObjectOf
import io.vertx.kotlin.coroutines.CoroutineVerticle
import io.vertx.kotlin.coroutines.coAwait
import io.vertx.mysqlclient.MySQLBuilder
import io.vertx.mysqlclient.MySQLConnectOptions
import io.vertx.sqlclient.Pool
import io.vertx.sqlclient.PoolOptions

class SharedDatabaseVerticle : CoroutineVerticle() {
  val logger: Logger = LoggerFactory.getLogger(javaClass.name)
  lateinit var dbPool: Pool

  override suspend fun start() {
    val dbConfig = ConfigRetriever.create(
      vertx, configRetrieverOptionsOf(
        stores = listOf(
          configStoreOptionsOf(
            type = "file",
            config = jsonObjectOf(Pair("path", "conf/db.json"))
          )
        )
      )
    ).config.coAwait()
    val dbPoolConfig = dbConfig.getJsonObject("pool", jsonObjectOf())
    dbPool = MySQLBuilder.pool().with(
      PoolOptions(dbPoolConfig).setShared(true)
    ).connectingTo(
      MySQLConnectOptions(dbConfig)
    ).using(vertx).build()
    logger.info("started")
  }

  override suspend fun stop() {
    logger.info("stopped")
    super.stop()
  }
}
